package neu.edu.vn.appmusic.ui;

import java.util.ArrayList;

import neu.edu.vn.appmusic.R;
import neu.edu.vn.appmusic.adapter.SongAdapter;
import neu.edu.vn.appmusic.object.Song;
import neu.edu.vn.appmusic.utils.music.MyMusic;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class FragmentOffline extends Fragment {
	
	private ArrayList<Song> arraySong = new ArrayList<Song>();
	private SongAdapter songAdapter;
	private ListView lvOfflineMusic;
	
	private MyMusic myMusic;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
//		setTitleFragmemt();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_offline, container, false);
		return rootView;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initGUI();
	}
	
	public void setTitleFragmemt(){
		Bundle args = new Bundle();
		args.putString("title", getResources().getString(R.string.fragment_name_offline));
		this.setArguments(args);
	}
	
	public void initGUI(){
		lvOfflineMusic = (ListView) getView().findViewById(R.id.lvOfflineMusic);
		songAdapter = new SongAdapter(getActivity(), R.layout.item_list_row, arraySong);
		lvOfflineMusic.setAdapter(songAdapter);
		getDataFormDevice();
		songAdapter.notifyDataSetChanged();
	}
	
	private void getDataFormDevice() {
		ContentResolver musicResolver = getActivity().getContentResolver();
		Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
		Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
		
		if(musicCursor!=null && musicCursor.moveToFirst()){
			  //get columns
			  int titleColumn = musicCursor.getColumnIndex
			    (android.provider.MediaStore.Audio.Media.TITLE);
			  int idColumn = musicCursor.getColumnIndex
			    (android.provider.MediaStore.Audio.Media._ID);
			  int artistColumn = musicCursor.getColumnIndex
			    (android.provider.MediaStore.Audio.Media.ARTIST);
			  //add songs to list
			  do {
			    long thisId = musicCursor.getLong(idColumn);
			    String thisTitle = musicCursor.getString(titleColumn);
			    String thisArtist = musicCursor.getString(artistColumn);
			    arraySong.add(new Song(thisTitle, thisArtist));
			  }
			  while (musicCursor.moveToNext());
			}
	}
}
